/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.version.model;

import java.io.InputStream;
import java.util.Calendar;
import javax.jcr.AccessDeniedException;
import javax.jcr.InvalidItemStateException;
import javax.jcr.Item;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.ItemVisitor;
import javax.jcr.MergeException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.Lock;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import offset.nodes.Constants;
import org.apache.jackrabbit.core.SessionImpl;

/**
 *
 * @author Walter L�tgenau
 */
public class FrozenNode implements Node {
    Node frozenNode;
    Node frozenParent = null;
    String name = null;
    VersionModel model;

    public FrozenNode(Node frozenNode) throws RepositoryException {
        this.frozenNode = frozenNode;
        this.model = new VersionModel(frozenNode.getSession());
    }

    public FrozenNode(Node frozenNode, Node parent, String name) throws RepositoryException {
        this(frozenNode);
        this.frozenParent = parent;
        this.name = name;
    }

    public void update(String srcWorkspaceName) throws NoSuchWorkspaceException, AccessDeniedException, LockException, InvalidItemStateException, RepositoryException {
        frozenNode.update(srcWorkspaceName);
    }

    public void unlock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException {
        frozenNode.unlock();
    }

    public Property setProperty(String name, Node value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public Property setProperty(String name, Calendar value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public Property setProperty(String name, long value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public Property setProperty(String name, double value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public Property setProperty(String name, boolean value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public Property setProperty(String name, InputStream value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public Property setProperty(String name, String value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value, type);
    }

    public Property setProperty(String name, String value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public Property setProperty(String name, String[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, values, type);
    }

    public Property setProperty(String name, String[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, values);
    }

    public Property setProperty(String name, Value[] values, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, values, type);
    }

    public Property setProperty(String name, Value[] values) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, values);
    }

    public Property setProperty(String name, Value value, int type) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value, type);
    }

    public Property setProperty(String name, Value value) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException {
        return frozenNode.setProperty(name, value);
    }

    public void restoreByLabel(String versionLabel, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException {
        frozenNode.restoreByLabel(versionLabel, removeExisting);
    }

    public void restore(Version version, String relPath, boolean removeExisting) throws PathNotFoundException, ItemExistsException, VersionException, ConstraintViolationException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException {
        frozenNode.restore(version, relPath, removeExisting);
    }

    public void restore(Version version, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, RepositoryException {
        frozenNode.restore(version, removeExisting);
    }

    public void restore(String versionName, boolean removeExisting) throws VersionException, ItemExistsException, UnsupportedRepositoryOperationException, LockException, InvalidItemStateException, RepositoryException {
        frozenNode.restore(versionName, removeExisting);
    }

    public void removeMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException {
        frozenNode.removeMixin(mixinName);
    }

    public void orderBefore(String srcChildRelPath, String destChildRelPath) throws UnsupportedRepositoryOperationException, VersionException, ConstraintViolationException, ItemNotFoundException, LockException, RepositoryException {
        frozenNode.orderBefore(srcChildRelPath, destChildRelPath);
    }

    public NodeIterator merge(String srcWorkspace, boolean bestEffort) throws NoSuchWorkspaceException, AccessDeniedException, MergeException, LockException, InvalidItemStateException, RepositoryException {
        return frozenNode.merge(srcWorkspace, bestEffort);
    }

    public Lock lock(boolean isDeep, boolean isSessionScoped) throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, InvalidItemStateException, RepositoryException {
        return frozenNode.lock(isDeep, isSessionScoped);
    }

    public boolean isNodeType(String nodeTypeName) throws RepositoryException {
        String primaryNodeType = frozenNode.getProperty(Constants.JCR_FROZEN_PRIMARY_TYPE).getString();
        if (primaryNodeType.equals(nodeTypeName))
            return true;
        
        NodeTypeManager nodeTypeManager = ((SessionImpl) frozenNode.getSession()).getNodeTypeManager();
        NodeType nodeType = nodeTypeManager.getNodeType(primaryNodeType);

        for (NodeType superType : nodeType.getSupertypes()) {
            if (superType.getName().equals(nodeTypeName))
                return true;
        }

        return false;
    }

    public boolean isLocked() throws RepositoryException {
        return frozenNode.isLocked();
    }

    public boolean isCheckedOut() throws RepositoryException {
        return frozenNode.isCheckedOut();
    }

    public boolean holdsLock() throws RepositoryException {
        return frozenNode.holdsLock();
    }

    public boolean hasProperty(String relPath) throws RepositoryException {
          return frozenNode.hasProperty(convertPropertyName(relPath));
    }

    public boolean hasProperties() throws RepositoryException {
        return frozenNode.getProperties().getSize() - 2 > 0;
    }

    public boolean hasNodes() throws RepositoryException {
        return frozenNode.hasNodes();
    }

    public boolean hasNode(String relPath) throws RepositoryException {
        return frozenNode.hasNode(relPath);
    }

    public VersionHistory getVersionHistory() throws UnsupportedRepositoryOperationException, RepositoryException {
        return frozenNode.getVersionHistory();
    }

    public String getUUID() throws UnsupportedRepositoryOperationException, RepositoryException {
        return frozenNode.getUUID();
        //return frozenNode.getProperty(Constants.JCR_FROZEN_UUID).getString();
    }

    public PropertyIterator getReferences() throws RepositoryException {
        return frozenNode.getReferences();
    }

    public Property getProperty(String relPath) throws PathNotFoundException, RepositoryException {
        return frozenNode.getProperty(convertPropertyName(relPath));
    }

    public PropertyIterator getProperties(String namePattern) throws RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public PropertyIterator getProperties() throws RepositoryException {
        return new FrozenNodePropertyIterator(frozenNode.getProperties());
    }

    public NodeType getPrimaryNodeType() throws RepositoryException {
        NodeTypeManager nodeTypeManager = getNodeTypeManager(frozenNode);
        return nodeTypeManager.getNodeType(frozenNode.getProperty(Constants.JCR_FROZEN_PRIMARY_TYPE).getString());
    }

    public Item getPrimaryItem() throws ItemNotFoundException, RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public NodeIterator getNodes(String namePattern) throws RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public NodeIterator getNodes() throws RepositoryException {
        return new FrozenNodeNodeIterator(frozenNode.getNodes());
    }

    public Node getNode(String relPath) throws PathNotFoundException, RepositoryException {
        Node child =  frozenNode.getNode(relPath);
        if (child.isNodeType(Constants.JCR_FROZEN_NODE))
            return new FrozenNode(child);
        else if (child.isNodeType(Constants.NT_VERSIONED_CHILD))
            return new FrozenNode(model.getFrozenNode(child));
        return null;
    }

    public NodeType[] getMixinNodeTypes() throws RepositoryException {
        return new NodeType[0];
    }

    public Lock getLock() throws UnsupportedRepositoryOperationException, LockException, AccessDeniedException, RepositoryException {
        return frozenNode.getLock();
    }

    public int getIndex() throws RepositoryException {
        return frozenNode.getIndex();
    }

    protected NodeTypeManager getNodeTypeManager(Node node) throws RepositoryException  {
        return ((SessionImpl) node.getSession()).getNodeTypeManager();
    }

    public NodeDefinition getDefinition() throws RepositoryException {
        // for child frozen nodes, we can use the definition, that matches a child definition of the original node
        Node parent = frozenNode.getParent();
        if (frozenParent != null)
            parent = frozenParent;
        if (parent.isNodeType(Constants.NT_FROZEN_NODE)) {
            NodeType primaryType = getNodeTypeManager(frozenNode).getNodeType(parent.getProperty(Constants.JCR_FROZEN_PRIMARY_TYPE).getString());
            for (NodeDefinition childDefinition : primaryType.getChildNodeDefinitions()) {
                if (isNodeType(childDefinition.getDefaultPrimaryType().getName()))
                    return childDefinition;
            }
        }

        // for the topmost frozen node, we have no definition
        return frozenNode.getDefinition();
    }

    public String getCorrespondingNodePath(String workspaceName) throws ItemNotFoundException, NoSuchWorkspaceException, AccessDeniedException, RepositoryException {
        return frozenNode.getCorrespondingNodePath(workspaceName);
    }

    public Version getBaseVersion() throws UnsupportedRepositoryOperationException, RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void doneMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException {
        frozenNode.doneMerge(version);
    }

    public void checkout() throws UnsupportedRepositoryOperationException, LockException, RepositoryException {
        frozenNode.checkout();
    }

    public Version checkin() throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException, LockException, RepositoryException {
        return frozenNode.checkin();
    }

    public void cancelMerge(Version version) throws VersionException, InvalidItemStateException, UnsupportedRepositoryOperationException, RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public boolean canAddMixin(String mixinName) throws NoSuchNodeTypeException, RepositoryException {
        return frozenNode.canAddMixin(mixinName);
    }

    public Node addNode(String relPath, String primaryNodeTypeName) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException {
        return frozenNode.addNode(relPath, primaryNodeTypeName);
    }

    public Node addNode(String relPath) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException {
        return frozenNode.addNode(relPath);
    }

    public void addMixin(String mixinName) throws NoSuchNodeTypeException, VersionException, ConstraintViolationException, LockException, RepositoryException {
        frozenNode.addMixin(mixinName);
    }

    @Override
    public String getPath() throws RepositoryException {
        return frozenNode.getPath();
    }

    @Override
    public String getName() throws RepositoryException {
        if (name != null)
            return name;
        return frozenNode.getName();
    }

    @Override
    public Item getAncestor(int depth) throws ItemNotFoundException, AccessDeniedException, RepositoryException {
        return frozenNode.getAncestor(depth);
    }

    @Override
    public Node getParent() throws ItemNotFoundException, AccessDeniedException, RepositoryException {
        if (frozenParent != null)
            return new FrozenNode(frozenParent);
        if (frozenNode.getParent().isNodeType(Constants.NT_FROZEN_NODE))
            return new FrozenNode(frozenNode.getParent());
        return frozenNode.getParent();
    }

    @Override
    public int getDepth() throws RepositoryException {
        return frozenNode.getDepth();
    }

    @Override
    public Session getSession() throws RepositoryException {
        return frozenNode.getSession();
    }

    @Override
    public boolean isNode() {
        return true;
    }

    @Override
    public boolean isNew() {
        return false;
    }

    @Override
    public boolean isModified() {
        return false;
    }

    @Override
    public boolean isSame(Item otherItem) throws RepositoryException {
        return frozenNode.isSame(otherItem);
    }

    @Override
    public void accept(ItemVisitor visitor) throws RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, ReferentialIntegrityException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void refresh(boolean keepChanges) throws InvalidItemStateException, RepositoryException {
        frozenNode.refresh(keepChanges);
    }

    @Override
    public void remove() throws VersionException, LockException, ConstraintViolationException, RepositoryException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * Convert the property name to simulate an "ordinary" node using
     * the frozen node.
     * 
     * @param propertyName
     * @return the simulated property name
     */
    protected String convertPropertyName(String propertyName) {
        if (propertyName.equals(Constants.JCR_PRIMARY_TYPE))
            return Constants.JCR_FROZEN_PRIMARY_TYPE;
        else if (propertyName.equals(Constants.JCR_UUID))
            return Constants.JCR_FROZEN_UUID;
        else
            return propertyName;
    }
}
